import json

from django import http
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection
from AJZF.libs.captcha.captcha import captcha
import logging
logger = logging.getLogger('django')
import random

class ImageCodeView(View):
    '''返回图形验证码的类视图'''

    def get(self, request):

        uuid = request.GET.get('cur')
        uuid2 = request.GET.get('pre')
        text, image = captcha.generate_captcha()
        redis_conn = get_redis_connection('verify_code')

        if uuid2:
            redis_conn.delete('img_%s' % uuid2)
        redis_conn.setex('img_%s' % uuid, 300, text)
        return http.HttpResponse(image,
                                 content_type='image/jpg')

class SMSCodeView(View):


    def post(self, request):

        dict = json.loads(request.body.decode())
        mobile = dict.get('mobile')
        uuid = dict.get('image_code_id')
        image_code_client = dict.get('image_code')

        if not all([image_code_client, uuid]):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '缺少必传参数'})

        # 3. 创建连接到redis的对象
        redis_conn = get_redis_connection('verify_code')

        # 4. 提取图形验证码
        image_code_server = redis_conn.get('img_%s' % uuid)
        if image_code_server is None:
            # 图形验证码过期或者不存在
            return http.JsonResponse({'code': 400,
                                      'errmsg': '图形验证码失效'})

        # 5. 删除图形验证码，避免恶意测试图形验证码
        # try:
        #     redis_conn.delete('img_%s' % uuid)
        # except Exception as e:
        #     logger.error(e)

        # 6. 对比图形验证码
        # bytes 转字符串
        image_code_server = image_code_server.decode()
        # 转小写后比较
        if image_code_client.lower() != image_code_server.lower():
            return http.JsonResponse({'code': 400,
                                      'errmsg': '输入图形验证码有误'})

        # 7. 生成短信验证码：生成6位数验证码
        phonecode = '%06d' % random.randint(0, 999999)
        logger.info(phonecode)

        # 8. 保存短信验证码
        # 短信验证码有效期，单位：300秒
        redis_conn.setex('sms_%s' % mobile,
                         300,
                         phonecode)

        # 往 redis 中写入一个数据, 写入什么不重要, 时间重要
        # 我们给写入的数据设置为60s,如果过期,则会获取不到.
        redis_conn.setex('send_flag_%s' % mobile, 60, 1)

        # 9. 发送短信验证码
        # 短信模板
        # CCP().send_template_sms(mobile,[sms_code, 5], 1)

        # 10. 响应结果
        return http.JsonResponse({'code': 0,
                                  'errmsg': '发送短信成功'})